package edu.umd.essic.maskbuilder;

import java.awt.print.*;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Component;
import java.awt.PrintGraphics;

public class MyPrint implements Printable{
    private Component componentToBePrinted;
    private double scale_factor;
    private static double page_width = 792;// 11 in
    private static double page_height= 612;// 8.5 in
    private static int margin = 50; //~0.7 in

    public MyPrint(javax.swing.JLabel iml, int width, int height) {
      componentToBePrinted = iml;  
      if (width > height) 
          scale_factor = (page_width-100) / width;
      else 
          scale_factor = (page_width-100) / height;
      PrinterJob printJob = PrinterJob.getPrinterJob(); 
      PageFormat pf = printJob.defaultPage();
      Paper paper = pf.getPaper();
      paper.setSize(page_height,page_width);  
      paper.setImageableArea(50,50,page_height-100,page_width-100); // to define margins
      pf.setPaper(paper); 
      if (width > height)
          pf.setOrientation(PageFormat.LANDSCAPE);
      printJob.setPrintable(this, pf);
      try {
         printJob.print();
      } catch(PrinterException pe) {
         System.out.println("Error printing: " + pe);
      }
   }

    public int print(Graphics g, PageFormat pf, int pi) throws PrinterException {
        if (pi >= 1) {
            return Printable.NO_SUCH_PAGE;
        }else{
            Graphics2D g2d = (Graphics2D)g;
            g2d.translate(pf.getImageableX(), pf.getImageableY());
            g2d.scale(scale_factor, scale_factor);
            g.translate(componentToBePrinted.getX(), componentToBePrinted.getY());
            componentToBePrinted.paint(g2d);
            return Printable.PAGE_EXISTS;
        }
    }
}
  